package com.xyw.his00.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xyw.his00.utils.NumberUtils.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;

public class JWTInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HashMap<String,Object> map=new HashMap<>();
        //获取请求头中的信息
        String token=request.getHeader("token");
        try {
            TokenUtil.verify(token);//验证令牌
            return true;
        }catch (SignatureVerificationException e){
            e.printStackTrace();
            map.put("msg", "无效签名！");
        }catch (TokenExpiredException e){
            e.printStackTrace();
            map.put("msg", "token过期！");
        }catch (AlgorithmMismatchException e){
            e.printStackTrace();
            map.put("msg", "token算法不一致！");
        }catch (Exception e){
            e.printStackTrace();
            map.put("msg", "token无效！");
        }

        map.put("state", false);
        String json = new ObjectMapper().writeValueAsString(map);
        System.out.println("json");
        //返回该拦截器拦截到的错误信息
        response.setContentType("application/json;charset=UTF-8");
        System.out.println(json);
        return false;
    }
}
